 //
//  AppDelegate.swift
//  SwiftWB
//
//  Created by 钟清 on 17/3/24.
//  Copyright © 2017年 Zhong Qing. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
       
        /*
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.rootViewController = MainViewController()
        window?.makeKeyAndVisible()
        */
        
        /* 统一设置外观颜色 */
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
        
        /* 注册监听 */
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.changeRootViewController(_:)), name: SwitchRootViewController, object: nil)
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.rootViewController = defaultViewController()
        window?.makeKeyAndVisible()
       
        UserAccount.loadUserAccount()
        
        return true
    }
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

extension AppDelegate {
    /* 切换根控制器 */
    func changeRootViewController(notice: NSNotification) {
        if notice.object as! Bool {
            window?.rootViewController = R.storyboard.main.initialViewController()
        } else {
            window?.rootViewController = R.storyboard.welcome.initialViewController()
        }
    }
    /* 获取对应控制器 */
    func defaultViewController() -> UIViewController {
        /* 判断是否登陆 */
        if UserAccount.isLogin() {
            /* 判断是否是新版本 */
            if isNewVersion() {
                return R.storyboard.newfeature.initialViewController()!
            } else {
                return R.storyboard.welcome.initialViewController()!
            }
        } else {
            return R.storyboard.main.initialViewController()!
        }
    }
    /* 新版本判断 */
    private func isNewVersion() -> Bool {
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        
        let defaults = NSUserDefaults.standardUserDefaults()
        let sandboxVersion = (defaults.valueForKey("preVersion") as? String) ?? "0.0"
        if currentVersion.compare(sandboxVersion) == NSComparisonResult.OrderedDescending {
            ZQLog("有新版本")
            defaults.setObject(currentVersion, forKey: "preVersion")
            defaults.synchronize() // ios7-需要
            return true
        }
        ZQLog("没有新版本")
        return false
    }
}

// 日志输出
func ZQLog<T>(message : T, fileName : String = #file, methodName : String = #function, lineNumber : Int = #line) {
    let fileLastName = (fileName as NSString).pathComponents.last!
    #if DEBUG
        print("\(fileLastName)\(methodName)[\(lineNumber)]:\(message)")
    #endif
    
}

